import React, { useEffect, useState } from "react";
import CategorySelector from "@/components/CategorySelector";
import { Button, Card, Form, Input, message, Space, Table, Tag } from "antd";
import { DeleteOutlined, FormOutlined, PlusOutlined } from "@ant-design/icons";
import { useSelectorCategory } from "@/store/slice/category";
import { addOrUpdateAttr, deleteAttr, getAttrList } from "@/api/sph";

function Attr() {
    const { category1Id, category2Id, category3Id } = useSelectorCategory();
    const [attrList, setAttrList] = useState([]);

    const [form] = Form.useForm();
    // 获取属性列表
    const getAttrListAsync = async () => {
        try {
            const res = await getAttrList(category1Id, category2Id, category3Id);
            setAttrList(res.data);
        } catch (e: any) {
            message.error(e.message);
        }
    };

    // 控制添加或修改属性的div的显示与隐藏
    const [modalVisible, setModalVisible] = useState(false);

    // 需要提交的数据
    const [submitData, setSubmitData] = useState<any>({
        attrName: "",
        attrValueList: [],
        categoryId: category3Id,
        categoryLevel: 3,
    });

    // 取消事件
    const handleCancel = () => {
        setModalVisible(false);
        // 还原表单
        form.resetFields();
    };
    // 添加属性
    const addAttr = () => {
        setModalVisible(true);
        // 每次添加重置表单
        setSubmitData({
            attrName: "",
            attrValueList: [],
            categoryId: category3Id,
            categoryLevel: 3,
        });
    };
    // 修改属性
    const updateAttr = (record: any) => {
        console.log(record);
        setModalVisible(true);
        setSubmitData({ ...record, attrValueList: [...record.attrValueList], isEdit: false });
        form.setFieldsValue(record);
    };
    // 添加属性值
    const addAttrValue = () => {
        submitData.attrName = form.getFieldValue("attrName");
        submitData.attrValueList.push({
            attrId: submitData.id,
            // 获取表单中的属性值
            valueName: "",
            isEdit: true,
            id: "",
        });
        // 设置提交数据
        setSubmitData({ ...submitData, attrValueList: [...submitData.attrValueList] });
    };
    // 编辑属性值
    const toEdit = (e: any, record: any) => {
        // 判断点击的是哪个属性值
        const index = submitData.attrValueList.findIndex((item: any) => item.id === record.id);
        // 修改属性值
        submitData.attrValueList[index].isEdit = true;
        setSubmitData({ ...submitData });
    };
    // 失去焦点
    const toLook = (e: any, record: any) => {
        record.valueName = e.target.value;
        // 判断点击的是哪个属性值
        const index = submitData.attrValueList.findIndex((item: any) => item.id === record.id);
        // 修改属性值
        submitData.attrValueList[index].isEdit = false;
        setSubmitData({ ...submitData });
    };

    // 保存
    const save = async () => {
        console.log(submitData);
        // 提交数据之前，需要将属性值的isEdit属性去掉
        submitData.attrValueList.forEach((item: any) => {
            delete item.isEdit;
        });
        // 提交数据
        try {
            // 判断是添加还是修改
            if (submitData.id) {
                // 修改
                addOrUpdateAttr(submitData).then((res) => {
                    message.success("修改成功");
                    setModalVisible(false);
                    getAttrListAsync();
                });
            } else {
                // 添加
                addOrUpdateAttr(submitData).then((res) => {
                    message.success("添加成功");
                    setModalVisible(false);
                    getAttrListAsync();
                });
            }
            form.resetFields();
        } catch (e: any) {
            message.error(e.message);
        }
    };

    // 删除属性
    const deleteAttrAsync = async (record: any) => {
        try {
            await deleteAttr(record.id);
            message.success("删除成功");
            getAttrListAsync();
        } catch (e: any) {
            message.error(e.message);
        }
    };
    // 删除属性值
    const deleteAttrValue = (record: any) => {
        console.log(record);
        // 判断点击的是哪个属性值
        const index = submitData.attrValueList.findIndex((item: any) => item.id === record.id);
        // 删除属性值
        submitData.attrValueList.splice(index, 1);
        console.log(submitData);
        setSubmitData({ ...submitData, attrValueList: [...submitData.attrValueList] });
    };

    // 当category3Id发生变化时，重新获取属性列表
    useEffect(() => {
        if (category3Id) {
            getAttrListAsync();
        }
    }, [category3Id]);

    return (
        <div style={{ marginLeft: 20, marginRight: 20 }}>
            <div>
                <CategorySelector modalVisible={modalVisible}></CategorySelector>
            </div>
            <div>
                <Card style={{ marginTop: 20 }}>
                    <div style={{ display: modalVisible ? "none" : "block" }}>
                        <Space>
                            <Button
                                type="primary"
                                icon={<PlusOutlined />}
                                onClick={() => addAttr()}
                                disabled={!category3Id}
                            >
                                添加属性
                            </Button>
                        </Space>
                        <Table
                            style={{ marginTop: 20 }}
                            bordered
                            dataSource={attrList}
                            rowKey={"id"}
                            columns={[
                                {
                                    title: "序号",
                                    dataIndex: "id",
                                    align: "center",
                                    width: 100,
                                    key: "id",
                                },
                                {
                                    title: "属性名称",
                                    dataIndex: "attrName",
                                    width: 200,
                                    align: "center",
                                    key: "attrName",
                                },
                                {
                                    title: "属性值列表",
                                    align: "left",
                                    key: "attrValueList",
                                    render: (record: any) =>
                                        record.attrValueList.map((item: any) => (
                                            <Tag color="blue" key={item.id}>
                                                {item.valueName}
                                            </Tag>
                                        )),
                                },
                                {
                                    title: "操作",
                                    align: "center",
                                    width: 200,
                                    key: "action",
                                    render: (record: any) => (
                                        <Space size="middle">
                                            <Button
                                                type="primary"
                                                icon={<FormOutlined />}
                                                onClick={() => updateAttr(record)}
                                            ></Button>
                                            <Button
                                                type="primary"
                                                danger
                                                icon={<DeleteOutlined />}
                                                onClick={() => deleteAttrAsync(record)}
                                            ></Button>
                                        </Space>
                                    ),
                                },
                            ]}
                        ></Table>
                    </div>
                    <div style={{ display: modalVisible ? "block" : "none" }}>
                        <Form form={form}>
                            <Form.Item label="属性名" name="attrName">
                                <Input placeholder={"请输入属性名"} style={{ width: 200 }}></Input>
                            </Form.Item>
                        </Form>
                        <Space>
                            <Button type={"primary"} onClick={addAttrValue}>
                                添加属性值
                            </Button>
                            <Button type={"default"} onClick={handleCancel}>
                                取消
                            </Button>
                        </Space>
                        <Table
                            style={{ marginTop: 20, marginBottom: 20 }}
                            dataSource={submitData.attrValueList}
                            rowKey={"id"}
                            columns={[
                                {
                                    title: "序号",
                                    dataIndex: "attrId",
                                    align: "center",
                                    width: 100,
                                    key: "attrId",
                                    render: (text: any, record: any, index: number) => index + 1,
                                },
                                {
                                    title: "属性值名称",
                                    align: "center",
                                    key: "valueName",
                                    render: (record: any) => (
                                        <Space>
                                            {record.isEdit ? (
                                                <Input
                                                    placeholder={"请输入属性值名称"}
                                                    autoFocus // 自动获取焦点
                                                    defaultValue={record.valueName}
                                                    onBlur={(e) => toLook(e, record)}
                                                    key={record.id}
                                                ></Input>
                                            ) : (
                                                <Tag color="blue" onClick={(e) => toEdit(e, record)} key={record.id}>
                                                    {record.valueName}
                                                </Tag>
                                            )}
                                        </Space>
                                    ),
                                },
                                {
                                    title: "操作",
                                    align: "center",
                                    key: "action",
                                    render: (record) => (
                                        <Space size="middle">
                                            <Button
                                                type="primary"
                                                danger
                                                icon={<DeleteOutlined />}
                                                onClick={() => deleteAttrValue(record)}
                                            ></Button>
                                        </Space>
                                    ),
                                },
                            ]}
                        ></Table>
                        <Space>
                            <Button type={"primary"} onClick={save}>
                                保存
                            </Button>
                            <Button type={"default"} onClick={handleCancel}>
                                取消
                            </Button>
                        </Space>
                    </div>
                </Card>
            </div>
        </div>
    );
}

export default Attr;
